//
//  ChooseGroupViewController.m
//  hello mui
//
//  Created by zhangtao on 15/9/22.
//  Copyright © 2015年 zt.td. All rights reserved.
//

#import "ChooseGroupViewController.h"
#import "GradeTableViewCell.h"
#import "Area.h"
#import "Group.h"
#import "City.h"

#define COL [UIColor colorWithRed:23/255.f green:170/255.f blue:71/255.f alpha:1]

@interface ChooseGroupViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *shengL;
@property (weak, nonatomic) IBOutlet UILabel *shiL;

@property (weak, nonatomic) IBOutlet UILabel *xianL;
@property (strong, nonatomic) IBOutlet UIButton *provinceBtn;
@property (strong, nonatomic) IBOutlet UIButton *cityBtn;
@property (strong, nonatomic) IBOutlet UIButton *areaBtn;

@property(nonatomic,strong)NSString *select; //btn
@property(nonatomic,assign)NSInteger selectCell;
@property(nonatomic,strong)UIImageView *imageIV;

@property (strong, nonatomic) IBOutlet UITableView *listTable;

@property (weak, nonatomic) IBOutlet UILabel *lowLabel;
@end

@implementation ChooseGroupViewController


-(void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
}

//-(void)viewWillDisappear:(BOOL)animated{
//
//}

- (void)viewDidLoad {
    [super viewDidLoad];

   
    self.listTable.backgroundColor = VIEWCO;
    _shengL.backgroundColor= _provinceBtn.tintColor = COL;
    
    _cityBtn.tintColor = _areaBtn.tintColor = [UIColor blackColor];
    self.automaticallyAdjustsScrollViewInsets = false;

    self.title = @"地区";
    [self setExtraCellLineHidden:_listTable];
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self getGroupRequest];
    _select = @"shengName";
    _listTable.delegate = self;
    _listTable.dataSource = self;
    _selectCell = -1;
//    [self initArray];  //本地文件读取地区
//    [self getGroupRequest];  //get 请求获取地区
    self.automaticallyAdjustsScrollViewInsets = false;
}

-(void)getGroupRequest{
    _groupArray = [NSMutableArray array];
    _cityArray = [NSMutableArray array];
    _areaArray = [NSMutableArray array];
    _array = [NSMutableArray array];
    NSString *path = @"personalCenter/getArea";
    
   [[HttpConnctionManager sharedInstance]PostRequestParam:nil andUrl:path andSuccessedArrayBlock:^(NSArray *succeedResult) {
//       NSLog(@"%@",succeedResult);
       //
       
      
       for (id obj in succeedResult) {
           [_groupArray addObject:obj];
       }
      
       for (NSDictionary *dic in _groupArray) {
           Group *group = [[Group alloc]init];
            group.shiArray = [NSMutableArray array];
           group.shengName = [dic valueForKey:@"shengName"];
          
           group.shengID = [dic valueForKey:@"shengID"];
           
           group.shiArray = [dic arrayWithFilted:@"shiList"];
           [_array addObject:group];
           
          
       }
       
       [_listTable reloadData];
       NSLog(@"request");

   } andFailedBlock:^(AFHTTPRequestOperation *response, NSError *error) {
       NSLog(@"requesterror");

       //
   }];
}


-(void)initArray{
    _pro = _city = @"";
    _array = [NSMutableArray array];
    NSString *proPath = [[NSBundle mainBundle]pathForResource:@"province" ofType:@"plist"];
    NSString *cityPath = [[NSBundle mainBundle]pathForResource:@"citydict" ofType:@"plist"];
    
    _proArray = [NSMutableArray arrayWithContentsOfFile:proPath];
    [_array addObjectsFromArray:_proArray];
    
   _cityDic = [NSMutableDictionary dictionaryWithContentsOfFile:cityPath];
    _cityArray = [NSMutableArray array];
    _keyArray = [NSMutableArray array];
    [_keyArray addObjectsFromArray:[[_cityDic allKeys] sortedArrayUsingSelector:@selector(compare:)]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}


- (IBAction)province:(id)sender {
    
    _select = @"group";
    _array = _groupArray;
    [_listTable reloadData];
    NSLog(@"province");
    

    
    
}

- (IBAction)city:(id)sender {
//    _select = @"city";
//   
//    _array = _cityArray;
//        _array = [NSMutableArray array];

    [_listTable reloadData];
//    NSLog(@"city");
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (_array.count ==_proArray.count) {
        return nil;
    }else{
    UIView *headIV = [[UIView alloc]init];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 2, 12, 12)];
    label.text = _keyArray[section];
    [headIV addSubview:label];
    return headIV;
    }
}

- (IBAction)areaBtn:(id)sender {
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _array ?_array.count : 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIndeter = @"cellIndeter";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndeter];
    if (!cell) {
        UITableViewCell *cell = [[UITableViewCell alloc]init ];
    
        cell.textLabel.text =[_array[indexPath.row] valueForKey:_select];//
        if (_selectCell == indexPath.row) {
            _imageIV.image = [UIImage imageNamed:@"item_selected.png"];
            [cell addSubview:_imageIV];
        }


        if (indexPath.row == 0 ) {
            UILabel *topL = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, MAIN_WIDTH, 1)];
            topL.backgroundColor = RGB(215, 215, 215, 1);
            [cell addSubview:topL];
            
        }else if(indexPath.row == (_array.count-1)) {
            UILabel *topL = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, MAIN_WIDTH, 1)];
            topL.backgroundColor = RGB(220, 220, 220, 1);
            [cell addSubview:topL];
            
//            cell.layer.borderWidth = 0;
//            cell.layer.borderColor = [[UIColor redColor]CGColor];//[RGB(210, 210, 210, 1)CGColor];
            UILabel *headL = [[UILabel alloc]initWithFrame:CGRectMake(0, 39, MAIN_WIDTH, 1)];
            headL.backgroundColor = RGB(215, 215, 215, 1);
            [cell addSubview:headL];
        }else{
            UILabel *topL = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, MAIN_WIDTH, 1)];
            topL.backgroundColor = RGB(220, 220, 220, 1);
            [cell addSubview:topL];
        }

        
        return cell;
    }
    
         cell.textLabel.text =[_array[indexPath.row] valueForKey:_select];//
//            if (indexPath.row == 0 ) {
//                UILabel *topL = [[UILabel alloc]initWithFrame:CGRectMake(0, -1, MAIN_WIDTH, 5)];
//                topL.backgroundColor = [UIColor redColor];//[UIColor colorWithRed:230/255.0f green:230/255.0f blue:230/255.0f alpha:1];
//                [cell addSubview:topL];
//    
//            }
//    
//                if (indexPath.row == (_array.count-1)) {
//                    UILabel *headL = [[UILabel alloc]initWithFrame:CGRectMake(0, 40, MAIN_WIDTH, 5)];
//                    headL.backgroundColor = [UIColor redColor];//[UIColor colorWithRed:230/255.0f green:230/255.0f blue:230/255.0f alpha:1];
//                    [cell addSubview:headL];
//                }
    
            
    
    
    return cell;

    //        if (indexPath.row == 0 ) {
    //            UILabel *topL = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, MAIN_WIDTH, 1)];
    //            topL.backgroundColor = [UIColor redColor];//[UIColor colorWithRed:230/255.0f green:230/255.0f blue:230/255.0f alpha:1];
    //            [cell addSubview:topL];
    //
    //        }
    //        if (_array) {
    //            if (indexPath.row == (_array.count-1)) {
    //                UILabel *headL = [[UILabel alloc]initWithFrame:CGRectMake(0, 39, MAIN_WIDTH, 1)];
    //                headL.backgroundColor = [UIColor redColor];//[UIColor colorWithRed:230/255.0f green:230/255.0f blue:230/255.0f alpha:1];
    //                [cell addSubview:headL];
    //            }
    //
    //        }
    
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    _shengL.backgroundColor = _shiL.backgroundColor = _xianL.backgroundColor = [UIColor clearColor];
    
    _provinceBtn.tintColor = _cityBtn.tintColor = _areaBtn.tintColor = [UIColor blackColor];
//    NSLog(@"~~~~~~%@",[_groupArray[indexPath.row]valueForKey:@"shengName"]);
    if ([_provinceBtn.titleLabel.text isEqualToString:@"省、直辖市"]) {
        self.shiL.backgroundColor = self.cityBtn.tintColor = COL;
        
        [_provinceBtn setTitle:[_groupArray[indexPath.row]valueForKey:@"shengName"] forState:UIControlStateNormal];
//        NSLog(@"12~sheng%@",[_groupArray[indexPath.row]valueForKey:@"shengID"]);
        NSUSER_DEF_NORSET([_groupArray[indexPath.row]valueForKey:@"shengID"], @"shengID");
        _array = [NSMutableArray array];
        _select = @"shiName";
        for (id obj in [_groupArray[indexPath.row]valueForKey:@"shiList"]) {
            [_cityArray addObject: obj];
        }
        
        for (id  obj in _cityArray) {
            City *city = [[City alloc]init];
            city.shiName = [obj valueForKey:@"shiName"];
            city.shiID = [obj valueForKey:@"shiID"];
            city.areaArray = [obj valueForKey:@"areaList"];
            [_array addObject:city];
            NSLog(@"****%@",_cityArray);
        }


        
    }else if([_cityBtn.titleLabel.text isEqualToString:@"市"]){
   
        self.xianL.backgroundColor = self.areaBtn.tintColor = COL;
         [_cityBtn setTitle:[_cityArray[indexPath.row]valueForKey:@"shiName"] forState:UIControlStateNormal];
//        NSLog(@"12~shi%@",[_cityArray[indexPath.row]valueForKey:@"shiID"]);
        NSUSER_DEF_NORSET([_cityArray[indexPath.row]valueForKey:@"shiID"], @"shiID");
        _array = [NSMutableArray array];
        _select = @"areaName";
        
        for (id obj in [_cityArray[indexPath.row]valueForKey:@"areaList"]) {
            [_areaArray addObject:obj];
        }
        
        for ( id obj in _areaArray) {
            Area *area = [[Area alloc]init];
            area.areaName = [obj stringWithFilted:@"areaName"];
            area.areaID = [obj stringWithFilted:@"areaID"];
            [_array addObject:area];
            
        }
        
    }else{
        self.xianL.backgroundColor = _areaBtn.tintColor = COL;
        [_areaBtn setTitle:[_areaArray[indexPath.row]valueForKey:@"areaName"] forState:UIControlStateNormal];
        NSUSER_DEF_NORSET([_areaArray[indexPath.row]valueForKey:@"areaID"], @"areaID");
//        _array = [NSMutableArray array];
        
        _selectCell = indexPath.row;
        [_imageIV removeFromSuperview];
        _imageIV = [[UIImageView alloc]initWithFrame:CGRectMake(MAIN_WIDTH-40, 5, 25, 25)];
        
         _change.groupLabel.text = [[NSString stringWithFormat:@"%@",_cityBtn.titleLabel.text] stringByAppendingString:[NSString stringWithFormat:@"%@",[_areaArray[indexPath.row]valueForKey:@"areaName"]]];
        NSUSER_DEF_NORSET(_change.groupLabel.text, @"GROUP");
        [self request];

        [self.navigationController popViewControllerAnimated:YES];

    }
    [_listTable reloadData];


}

-(void)request{
    NSString *path = @"personalCenter/updateReadInfo";
    NSString *userId = [NSString stringWithFormat:@"%@",NSUSER_DEF(@"USERID")];
    NSString *shengId = [NSString stringWithFormat:@"%@",NSUSER_DEF(@"shengID")];
    NSString *shiId = [NSString stringWithFormat:@"%@",NSUSER_DEF(@"shiID")];
    NSString *areaId = [NSString stringWithFormat:@"%@",NSUSER_DEF(@"areaID")];

    
    NSDictionary *dic = @{@"userId":userId,@"shengId": shengId,@"shiId":shiId ,@"areaId":areaId};
    NSDictionary *dics =  @{@"userId":userId,@"shengId": shengId,@"shiId":shiId ,@"areaId":areaId,@"bd_sig":[ToolObjc md5Str:dic]};
    
    [[HttpConnctionManager sharedInstance]requestParam:dics andUrl:path andSuccessedBlock:^(NSDictionary *succeedResult) {
        NSLog(@"%@%@",[succeedResult valueForKey:@"resCode"],[succeedResult valueForKey:@"resMessage"]);
    } andFailedBlock:^(AFHTTPRequestOperation *response, NSError *error) {
        
    }];
    
    

}

@end
